/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.omega_r.libs.omegarecyclerview.viewpager.default_transformers;

import com.omega_r.libs.omegarecyclerview.viewpager.OmegaPagerRecyclerView.PageTransformer;
import ohos.agp.components.Component;

public abstract class ABaseTransformer implements PageTransformer {

    static float min(float value, float m) {
        return Math.max(value, m);
    }

    @Override
    public void transformPage(Component component, float position) {
        float clampedPosition = clampPosition(position);
        onPreTransform(component, clampedPosition);
        onTransform(component, clampedPosition);
        onPostTransform(component, clampedPosition);
    }

    protected void onPreTransform(Component component, float position) {
        float width = (float) component.getWidth();
        component.setRotation(0.0F);
        component.setScaleX(1.0F);
        component.setScaleY(1.0F);
        component.setPivotX(0.0F);
        component.setPivotY(0.0F);
        component.setTranslationY(0.0F);
        component.setTranslationX(isPagingEnabled() ? 0.0F : -width * position);
        if (hideOffscreenPages()) {
            if (position <= -1f || position >= 1f) {
                component.setAlpha(0f);
            } else {
                component.setAlpha(1f);
            }
            component.setEnabled(false);
        } else {
            component.setEnabled(true);
            component.setAlpha(1.0F);
        }
    }

    private float clampPosition(float position) {
        float clampPosition;
        if (position <= -1F) {
            clampPosition = -1.0F;
        } else if (position >= 1F) {
            clampPosition = 1.0F;
        } else if (Float.isNaN(position)) {
            clampPosition = 0.0F;
        } else {
            clampPosition = position;
        }
        return clampPosition;
    }

    public boolean isPagingEnabled() {
        return false;
    }

    protected boolean hideOffscreenPages() {
        return true;
    }

    protected void onPostTransform(Component component, float position) {
    }

    protected abstract void onTransform(Component component, float position);
}
